﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace AGuang.WebTool.Controls {
    public class NumericPager:Control,IPostBackEventHandler {
        /// <summary>参数集合</summary>
        protected Dictionary<String, Object> paramDic = new Dictionary<string, object>();

        /// <summary>
        /// 取得总页数
        /// </summary>
        public int PageCount {
            get {
                int count = RecordCount / PageSize;
                if (RecordCount % PageSize > 0) count++;
                if (count == 0) count = 1;
                return count;
            }
        }

        /// <summary>
        /// 记录总数
        /// </summary>
        public int RecordCount {
            get {
                Object obj = ViewState["RecordCount"];
                if (obj == null) return 20;
                else return (int)obj;
            }
            set { ViewState["RecordCount"] = value; }
        }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int CurrentPage {
            get {
                Object obj = ViewState["CurrentPage"];
                if (obj == null) {
                    if (Mode == NumericPagerMode.Link) {
                        String v = Page.Request.QueryString[PageParamName];
                        int p;
                        if (Int32.TryParse(v, out p)) {
                            return p;
                        } else return 1;
                    } else return 1;
                } else return (int)obj;

            }
            set { ViewState["CurrentPage"] = value; }
        }

       /// <summary>
       /// 页面大小，默认为20
       /// </summary>
        public int PageSize {
            get {
                Object obj = ViewState["PageSize"];
                if (obj == null) return 20;
                else return (int)obj;
            }
            set { ViewState["PageSize"] = value; }
        }

        /// <summary>
        /// 当前页的记录数
        /// </summary>
        public int CurrentRecordCount {
            get{
                if (CurrentPage < PageCount) return PageSize;
                int residue = RecordCount % PageSize;
                if (residue == 0) return PageSize;
                else return residue;
            }
        }

        /// <summary>
        /// 显示页码数
        /// </summary>
        public int NumericCount {
            get {
                Object obj = ViewState["NumericCount"];
                if (obj == null) return 10;
                else return (int)obj;
            }
            set { ViewState["NumericCount"] = value; }
        }

        /// <summary>
        /// 翻页链接的样式
        /// </summary>
        public String LinkClass {
            get {
                Object obj = ViewState["LinkClass"];
                if (obj == null) return String.Empty;
                else return (String)obj;
            }
            set { ViewState["LinkClass"] = value; }
        }

        public String LinkStyle {
            get {
                Object obj = ViewState["LinkStyle"];
                if (obj == null) return String.Empty;
                else return (String)obj;
            }
            set { ViewState["LinkStyle"] = value; }
        }

        /// <summary>
        /// 当前页页码的样式
        /// </summary>
        public String CurrentPageClass {
            get {
                Object obj = ViewState["CurrentPageClass"];
                if (obj == null) return String.Empty;
                else return (String)obj;
            }
            set { ViewState["CurrentPageClass"] = value; }
        }

        /// <summary>
        /// 显示首页和尾页的翻页链接
        /// </summary>
        public bool ShowFirstAndEndPager {
            get {
                Object obj = ViewState["ShowFirstAndEndPager"];
                if (obj == null) return true;
                else return (bool)obj;
            }
            set { ViewState["ShowFirstAndEndPager"] = value; }
        }

        /// <summary>
        /// 当前页页码的样式
        /// </summary>
        public String CurrentPageStyle {
            get {
                Object obj = ViewState["CurrentPageStyle"];
                if (obj == null) return String.Empty;
                else return (String)obj;
            }
            set { ViewState["CurrentPageStyle"] = value; }
        }

        protected override void OnLoad(EventArgs e) {
            for (int i = 0; i < Page.Request.QueryString.Keys.Count; i++) {
                String key = Page.Request.QueryString.Keys[i];
                paramDic.Add(key, Page.Request.QueryString.GetValues(key));
            }
                base.OnLoad(e);
        }

        /// <summary>将内容输出到流</summary>
        protected override void Render(HtmlTextWriter writer) {
            //翻页的数字逻辑
            int half = NumericCount / 2;
            int endNum = CurrentPage + half;
            if (endNum > PageCount) endNum = PageCount;
            int startNum = endNum - NumericCount + 1;
            if (startNum < 1) { 
                startNum = 1;
                endNum = startNum + NumericCount - 1;
                if (endNum > PageCount) endNum = PageCount;
            }

            //生成页面链接
            if (CurrentPage > 1) {
                if (ShowFirstAndEndPager) writeALink(writer, 1, "首页");
                writeALink(writer, CurrentPage-1, "上一页");
            }
            for (int i = startNum; i <= endNum; i++) {
                if (i == CurrentPage) {
                    writeNoLink(writer, i.ToString());
                } else {
                    writeALink(writer, i,i.ToString()); 
                }
            }
            if (CurrentPage < PageCount) {
                writeALink(writer, CurrentPage+1, "下一页");
                if (ShowFirstAndEndPager) writeALink(writer, PageCount, "尾页");
            }
            base.Render(writer);
        }

        /// <summary>激发回传事件</summary>
        protected void OnPageChanged(EventArgs e) {
            EventHandler clickEventDelegate = (EventHandler)Events["PageChanged"];
            if (clickEventDelegate != null) {
                clickEventDelegate(this, e);
            }
        }

        /// <summary>激发回传事件</summary>
        void IPostBackEventHandler.RaisePostBackEvent(string argument) {
            int num;
            if (Int32.TryParse(argument, out num)) {
                CurrentPage = num;
                OnPageChanged(EventArgs.Empty);
            }
        }

        /// <summary>
        /// 翻页产生的事件，当Mode为Link时不产生该事件
        /// </summary>
        public event EventHandler PageChanged {
            add {
                Events.AddHandler("PageChanged", value);
            }
            remove {
                Events.RemoveHandler("PageChanged", value);
            }
        }

        /// <summary>
        /// 翻页控件的原理
        /// </summary>
        public NumericPagerMode Mode {
            get {
                Object obj = ViewState["Mode"];
                if (obj == null) return NumericPagerMode.PostBack;
                return (NumericPagerMode)obj;
            }
            set {
                ViewState["Mode"] = value;
            }
        }

        /// <summary>
        /// 当Mode为Link时使用，通过链接传递一些其他值
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="vlaue">值，可以为任何简单类型，简单类型的数组，集合也可</param>
        public void AddParam(String key, Object value) {
            paramDic[key] = value;
        }

        /// <summary>
        /// 当Mode为Link时使用，通过删除链接中将要传递的一些其他值
        /// </summary>
        /// <param name="key">参数名</param>
        public void RemoveParam(String key) {
            paramDic.Remove(key);
        }

        /// <summary>
        /// 传递页码的参数名
        /// </summary>
        public String PageParamName {
            get {
                String param = (String)ViewState["PageParamName"];
                if (String.IsNullOrEmpty(param)) return "p";
                else return param;
            }
            set {
                ViewState["PageParamName"] = value;
            }
        }

        /// <summary>
        /// 翻页链接的模板,如/page/{0}.html 主要用于生成伪静态链接,PageParamName 的值用于接收,应与UrlRewriter中的设置相对应
        /// </summary>
        public String PageLinkTemplate {
            get { return (String)ViewState["PageLinkTemplate"]; }
            set { ViewState["PageLinkTemplate"] = value; }
        }

        public enum NumericPagerMode { 
            /// <summary>利用页面回传原理的翻页</summary>
            PostBack,
            /// <summary>生成链接的翻页</summary>
            Link
        }

        #region 生成链接
        /// <summary>
        /// 生成一个页面链接
        /// </summary>
        /// <param name="writer">输出流</param>
        /// <param name="page">链到的页码</param>
        /// <param name="text">显示文字</param>
        private void writeALink(HtmlTextWriter writer, int page,String text) {
            writer.WriteBeginTag("a");
            if (!String.IsNullOrEmpty(LinkClass)) writer.WriteAttribute("class", LinkClass);
            if (!String.IsNullOrEmpty(LinkStyle)) writer.WriteAttribute("style", LinkStyle);
            if (this.Mode == NumericPagerMode.Link) {//链接
                if (String.IsNullOrEmpty(PageLinkTemplate)) {
                    paramDic[PageParamName] = page;
                    List<String> list = new List<string>();
                    foreach (KeyValuePair<String, Object> item in paramDic) {
                        if (item.Value is IEnumerable) {
                            IEnumerable l = (IEnumerable)item.Value;
                            IEnumerator it = l.GetEnumerator();
                            while (it.MoveNext()) {
                                list.Add(Page.Server.UrlEncode(item.Key) + "=" + Page.Server.UrlEncode(it.Current.ToString()));
                            }
                        } else {
                            list.Add(Page.Server.UrlEncode(item.Key) + "=" + Page.Server.UrlEncode(item.Value.ToString()));
                        }
                    }
                    writer.WriteAttribute("href", "?" + String.Join("&", list.ToArray()));
                } else {
                    writer.WriteAttribute("href", String.Format(PageLinkTemplate, page));
                }
            } else { //回调脚本
                writer.WriteAttribute("href", Page.ClientScript.GetPostBackClientHyperlink(this, page.ToString()));
            }
            writer.Write(HtmlTextWriter.TagRightChar);
            writer.WriteEncodedText(text);
            writer.WriteEndTag("a");
            writer.Write(" ");
        }

        /// <summary>
        /// 生成一个无链接的占位档
        /// </summary>
        /// <param name="writer">输出流</param>
        /// <param name="text">显示文字</param>
        private void writeNoLink(HtmlTextWriter writer, String text) {
            writer.WriteBeginTag("span");
            if (!String.IsNullOrEmpty(CurrentPageClass)) writer.WriteAttribute("class", CurrentPageClass);
            if (!String.IsNullOrEmpty(CurrentPageStyle)) writer.WriteAttribute("style", CurrentPageStyle);
            writer.Write(HtmlTextWriter.TagRightChar);
            writer.WriteEncodedText(text);
            writer.WriteEndTag("span");
            writer.Write(" ");
        }
        #endregion

    }


}
